from datetime import datetime

from common.response import Response
from models import Buy, Library, BuyVO, db

from util.jsonUtil import buy2dict, dict2buy, response2dict, buyVO2dict


#查询所有互借记录
def getAllBuyList():
    buyList = Buy.query.all()
    buyVOList = []
    for buy in buyList:
        library = Library.query.filter_by(library_name=buy.library_name).first()
        buyVO = BuyVO(buy, library)
        buyVOList.append(buyVO)
    code = "200"
    msg = "查询成功"
    data = [buyVO2dict(buyVO) for buyVO in buyVOList]
    response = Response(code, msg, data)
    return response2dict(response)


#根据用户Id查询借阅记录
def getBuyByUserId(user_id):
    buyList = list(Buy.query.filter_by(user_to_id=user_id))
    if buyList:
        buyVOList = []
        for buy in buyList:
            library = Library.query.filter_by(library_name=buy.library_name).first()
            buyVO = BuyVO(buy, library)
            buyVOList.append(buyVO)
        code = "200"
        msg = "查询成功"
        data = [buyVO2dict(buyVO) for buyVO in buyVOList]
        response = Response(code, msg, data)

    else:
        code = "404"
        msg = '获取失败，没有该userid的用户'
        data = ''
        response = Response(code, msg, data)
    return response2dict(response)


def creatBuy(buy):
    library = Library.query.filter_by(library_name=buy.library_name).first()
    if int(library.num) >= int(buy.num):
        library.num -= int(buy.num)
        db.session.commit()
        db.session.add(buy)
        db.session.commit()
        buyVO = BuyVO(buy, library)
        code = "200"
        msg = "添加成功"
        data = buyVO2dict(buyVO)
        response = Response(code, msg, data)
        return response2dict(response)
    else:
        code = "404"
        msg = '图书数量不足'
        data = ''
        response = Response(code, msg, data)
    return response2dict(response)


def returnBuy(id, buy0):
    buy = Buy.query.filter_by(buy_id=id).first()
    buy0.borrow_time = buy.borrow_time
    date = datetime.now()
    buy0.return_time = date
    db.session.delete(buy)
    db.session.commit()
    buy0.buy_id = id
    db.session.add(buy0)
    db.session.commit()
    library = Library.query.filter_by(library_name=buy.library_name).first()
    library.num += buy0.num
    db.session.commit()
    buyVO = BuyVO(buy0, library)
    code = "200"
    msg = "归还成功"
    data = buyVO2dict(buyVO)
    response = Response(code, msg, data)
    return response2dict(response)
